#include "datagendialog.h"
#include <QVBoxLayout>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QSpinBox>
#include <QTableWidget>
#include <QHeaderView>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QProgressBar>
#include <QMessageBox>
#include <QApplication>
#include <QSqlDatabase>
#include <QComboBox>
#include <QCheckBox>
#include <QDoubleSpinBox>

DataGenDialog::DataGenDialog(const QSqlDatabase &db, QWidget *parent)
    : QDialog(parent)
    , m_database(db)
    , m_dataGenerator(new DataGenerator(this))
    , m_generating(false)
{
    setupUI();
    updateUIState(false);
    
    connect(m_dataGenerator, &DataGenerator::generationProgress,
            this, &DataGenDialog::onGenerationProgress);
    connect(m_dataGenerator, &DataGenerator::generationFinished,
            this, &DataGenDialog::onGenerationFinished);
    connect(m_dataGenerator, &DataGenerator::generationError,
            this, &DataGenDialog::onGenerationError);
}

void DataGenDialog::addColumn()
{
    int row = m_columnsTable->rowCount();
    m_columnsTable->insertRow(row);
    
    // 列名
    QLineEdit *nameEdit = new QLineEdit;
    m_columnsTable->setCellWidget(row, 0, nameEdit);
    
    // 数据类型
    QComboBox *typeCombo = new QComboBox;
    typeCombo->addItem("VARCHAR(255)");
    typeCombo->addItem("INTEGER");
    typeCombo->addItem("REAL");
    typeCombo->addItem("DATE");
    typeCombo->addItem("DATETIME");
    typeCombo->addItem("TEXT");
    m_columnsTable->setCellWidget(row, 1, typeCombo);
    
    // 最小长度/值
    QSpinBox *minSpin = new QSpinBox;
    minSpin->setRange(0, 1000000);
    m_columnsTable->setCellWidget(row, 2, minSpin);
    
    // 最大长度/值
    QSpinBox *maxSpin = new QSpinBox;
    maxSpin->setRange(0, 1000000);
    maxSpin->setValue(100);
    m_columnsTable->setCellWidget(row, 3, maxSpin);
    
    // 可为空
    QCheckBox *nullCheck = new QCheckBox;
    m_columnsTable->setCellWidget(row, 4, nullCheck);
    
    // 为空概率
    QDoubleSpinBox *nullProbSpin = new QDoubleSpinBox;
    nullProbSpin->setRange(0.0, 1.0);
    nullProbSpin->setSingleStep(0.1);
    m_columnsTable->setCellWidget(row, 5, nullProbSpin);
}

void DataGenDialog::removeColumn()
{
    int row = m_columnsTable->currentRow();
    if (row >= 0) {
        m_columnsTable->removeRow(row);
    }
}

void DataGenDialog::generateData()
{
    // 收集表配置信息
    m_tableConfig.name = m_tableNameEdit->text().trimmed();
    if (m_tableConfig.name.isEmpty()) {
        QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a table name."));
        return;
    }
    
    m_tableConfig.rowCount = m_rowCountSpinBox->value();
    if (m_tableConfig.rowCount <= 0) {
        QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a valid row count."));
        return;
    }
    
    m_tableConfig.columns.clear();
    
    // 收集列配置信息
    for (int row = 0; row < m_columnsTable->rowCount(); ++row) {
        QLineEdit *nameEdit = qobject_cast<QLineEdit*>(m_columnsTable->cellWidget(row, 0));
        QComboBox *typeCombo = qobject_cast<QComboBox*>(m_columnsTable->cellWidget(row, 1));
        QSpinBox *minSpin = qobject_cast<QSpinBox*>(m_columnsTable->cellWidget(row, 2));
        QSpinBox *maxSpin = qobject_cast<QSpinBox*>(m_columnsTable->cellWidget(row, 3));
        QCheckBox *nullCheck = qobject_cast<QCheckBox*>(m_columnsTable->cellWidget(row, 4));
        QDoubleSpinBox *nullProbSpin = qobject_cast<QDoubleSpinBox*>(m_columnsTable->cellWidget(row, 5));
        
        if (!nameEdit || !typeCombo || !minSpin || !maxSpin || !nullCheck || !nullProbSpin) {
            QMessageBox::warning(this, tr("Error"), tr("Invalid column configuration."));
            return;
        }
        
        QString columnName = nameEdit->text().trimmed();
        if (columnName.isEmpty()) {
            QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a name for column %1.").arg(row + 1));
            return;
        }
        
        ColumnConfig colConfig;
        colConfig.name = columnName;
        colConfig.type = typeCombo->currentText();
        colConfig.minLength = colConfig.minValue = minSpin->value();
        colConfig.maxLength = colConfig.maxValue = maxSpin->value();
        colConfig.nullable = nullCheck->isChecked();
        colConfig.nullProbability = nullProbSpin->value();
        
        m_tableConfig.columns[columnName] = colConfig;
    }
    
    if (m_tableConfig.columns.isEmpty()) {
        QMessageBox::warning(this, tr("Invalid Input"), tr("Please add at least one column."));
        return;
    }
    
    // 开始生成数据
    updateUIState(true);
    m_dataGenerator->setDatabase(m_database);
    m_dataGenerator->generateData(m_tableConfig);
}

void DataGenDialog::cancelGeneration()
{
    m_dataGenerator->cancelGeneration();
}

void DataGenDialog::onGenerationProgress(int percentage)
{
    m_progressBar->setValue(percentage);
}

void DataGenDialog::onGenerationFinished(const QString &message)
{
    updateUIState(false);
    m_progressBar->setValue(100);
    QMessageBox::information(this, tr("Success"), message);
}

void DataGenDialog::onGenerationError(const QString &error)
{
    updateUIState(false);
    QMessageBox::warning(this, tr("Error"), error);
}

void DataGenDialog::setupUI()
{
    setWindowTitle(tr("Data Generator"));
    setModal(true);
    resize(700, 500);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 表基本信息
    QFormLayout *formLayout = new QFormLayout;
    
    m_tableNameEdit = new QLineEdit;
    formLayout->addRow(tr("Table Name:"), m_tableNameEdit);
    
    m_rowCountSpinBox = new QSpinBox;
    m_rowCountSpinBox->setRange(1, 1000000);
    m_rowCountSpinBox->setValue(100);
    formLayout->addRow(tr("Row Count:"), m_rowCountSpinBox);
    
    mainLayout->addLayout(formLayout);
    
    // 列配置标题
    QLabel *columnsLabel = new QLabel(tr("Column Configuration:"));
    mainLayout->addWidget(columnsLabel);
    
    // 列配置表
    m_columnsTable = new QTableWidget(0, 6);
    m_columnsTable->setHorizontalHeaderLabels({
        tr("Name"), tr("Type"), tr("Min Value/Length"), tr("Max Value/Length"),
        tr("Nullable"), tr("Null Probability")
    });
    m_columnsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    m_columnsTable->verticalHeader()->setVisible(false);
    mainLayout->addWidget(m_columnsTable);
    
    // 列操作按钮
    QHBoxLayout *columnButtonLayout = new QHBoxLayout;
    m_addColumnButton = new QPushButton(tr("Add Column"));
    m_removeColumnButton = new QPushButton(tr("Remove Column"));
    columnButtonLayout->addWidget(m_addColumnButton);
    columnButtonLayout->addWidget(m_removeColumnButton);
    columnButtonLayout->addStretch();
    mainLayout->addLayout(columnButtonLayout);
    
    // 进度条
    m_progressBar = new QProgressBar;
    m_progressBar->setValue(0);
    m_progressBar->setVisible(false);
    mainLayout->addWidget(m_progressBar);
    
    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    m_generateButton = new QPushButton(tr("Generate Data"));
    m_cancelButton = new QPushButton(tr("Cancel"));
    m_cancelButton->setVisible(false);
    
    buttonLayout->addWidget(m_generateButton);
    buttonLayout->addWidget(m_cancelButton);
    buttonLayout->addStretch();
    
    m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
    buttonLayout->addWidget(m_buttonBox);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号和槽
    connect(m_addColumnButton, &QPushButton::clicked, this, &DataGenDialog::addColumn);
    connect(m_removeColumnButton, &QPushButton::clicked, this, &DataGenDialog::removeColumn);
    connect(m_generateButton, &QPushButton::clicked, this, &DataGenDialog::generateData);
    connect(m_cancelButton, &QPushButton::clicked, this, &DataGenDialog::cancelGeneration);
    connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    
    // 添加一个示例列
    addColumn();
}

void DataGenDialog::updateUIState(bool generating)
{
    m_generating = generating;
    
    // 更新控件启用状态
    m_tableNameEdit->setEnabled(!generating);
    m_rowCountSpinBox->setEnabled(!generating);
    m_columnsTable->setEnabled(!generating);
    m_addColumnButton->setEnabled(!generating);
    m_removeColumnButton->setEnabled(!generating);
    m_generateButton->setEnabled(!generating);
    m_buttonBox->setEnabled(!generating);
    
    // 显示/隐藏生成相关控件
    m_cancelButton->setVisible(generating);
    m_progressBar->setVisible(generating);
    
    // 更新进度条
    if (!generating) {
        m_progressBar->setValue(0);
    }
}